package com.link.base.wechat.wxmessage.util;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.mpconfig.model.SendTempMessage;
import com.link.base.wechat.basic.util.WeixinHttpUtil;
import com.link.base.wechat.basic.util.WxExceptionUtil;
import com.link.base.wechat.wxmessage.model.WxMessage;
import com.link.base.wechat.wxmessage.model.WxTemplateMsg;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.JsonUtil;
import com.link.core.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号消息推送工具类
 *
 * @author lujiang
 * @date 2019/02/26 15:18
 */
public class WxMsgUtil {

    /**
     *  发送客服消息
     */
    public static final String SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";

    /**
     * 发送模板消息
     */
    public static final String SEND_TEMPMSG_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
    /**
     * 群发接口
     */
    public static final String SENDALL_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN";
    /**
     * 根据标签进行群发接口
     */
    public static final String SENDALL_TAG_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";
    /*发送订阅消息url*/
    public static final String SEND_SUB_MSG_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";

    private static final Logger logger = LogManager.getLogger(WxMsgUtil.class);

    /**
     * 发送客服消息
     *
     * @author lujiang
     * @date 2019-02-26 14:43
     * @param wxMessage 客服消息对象
     * @param accessToken 全局唯一接口调用凭据
     * @return
     * @throws Exception
     */
    public static int wxSendMsg(WxMessage wxMessage, String accessToken) throws Exception {
        Map<String, Object> map = new HashMap<>(16);
        if (StringUtils.isBlank(accessToken)) {
            throw new ServiceException("WXMSG-001");
        }
        // 发送主体
        String contents = wxMessage.getContents();
        // openid
        map.put("touser", wxMessage.getFromUserName());
        if (StringUtils.equals(wxMessage.getMsgType(),"text")) {
            // 文本
            Map<String, Object> textMap = new HashMap<>(16);
            textMap.put("content", contents);
            map.put("text", textMap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"image")) {
            // 图片
            Map<String, Object> mediaIdmap = new HashMap<>(16);
            mediaIdmap.put("media_id", contents);
            map.put("image", mediaIdmap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"mpnews")) {
            // 图文
            Map<String, Object> mpnewsmap = new HashMap<>(16);
            mpnewsmap.put("media_id", contents);
            map.put("mpnews", mpnewsmap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"wxcard")) {
            // 卡券
            Map<String, Object> wxcardmap = new HashMap<>(16);
            wxcardmap.put("card_id", contents);
            map.put("wxcard", wxcardmap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"miniprogrampage")) {
            //小程序卡片
            Map<String, Object> MpMap = new HashMap<>(16);
            MpMap.put("title", wxMessage.getTitle());
            MpMap.put("appid", wxMessage.getAppid());
            MpMap.put("pagepath", wxMessage.getPagepath());
            MpMap.put("thumb_media_id", wxMessage.getThumbMediaId());
            map.put("miniprogrampage", MpMap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"msgmenu")) {
            //发送菜单消息
            Map<String, Object> menuMap = new HashMap<>(16);
            menuMap.put("head_content", wxMessage.getHeadContent());
            menuMap.put("list", wxMessage.getList());
            menuMap.put("tail_content", wxMessage.getTailContent());
            map.put("msgmenu", menuMap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"music")) {
            //音乐
            Map<String, Object> musicMap = new HashMap<>(16);
            musicMap.put("title", wxMessage.getTitle());
            musicMap.put("description", wxMessage.getDescription());
            musicMap.put("musicurl", wxMessage.getMusicurl());
            musicMap.put("hqmusicurl", wxMessage.getHqmusicurl());
            musicMap.put("thumb_media_id", wxMessage.getThumbMediaId());
            map.put("music", musicMap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"video")) {
            //视频
            Map<String, Object> videoMap = new HashMap<>(16);
            videoMap.put("media_id", wxMessage.getThumbMediaId());
            videoMap.put("thumb_media_id", wxMessage.getThumbMediaId());
            videoMap.put("title", wxMessage.getTitle());
            videoMap.put("description", wxMessage.getDescription());
            map.put("video", videoMap);
        } else if (StringUtils.equals(wxMessage.getMsgType(), "news")) {
            // 网页链接或外链图文
            List<Map<String, String>> news = new ArrayList<>();
            Map<String, String> newMap = new HashMap<>(16);
            newMap.put("title", wxMessage.getTitle());
            newMap.put("description", wxMessage.getDescription());
            newMap.put("url", wxMessage.getPagepath());
            newMap.put("picurl", wxMessage.getPicurl());
            news.add(newMap);
            Map<String, Object> articles = new HashMap<>();
            articles.put("articles",news);
            map.put("news", articles);
        }
        map.put("msgtype", wxMessage.getMsgType());
        // 数据json字符串
        String msgJson = JsonUtil.toString(map);
        // 请求路径
        String requestUrl = SEND_URL.replace("ACCESS_TOKEN", accessToken);
        // 调用接口创建菜单
        JSONObject jsonObject = WeixinHttpUtil.httpRequest(requestUrl, "POST", msgJson);
        WxExceptionUtil.parse(jsonObject.toJSONString());
        int result = 1;
        return result;
    }

    /**
     * 模板消息
     *
     * @author lujiang
     * @date 2019/03/6 18:45
     * @param accessToken 全局唯一接口调用凭据
     * @param templateMsg 模板消息对象
     * @return
     * @throws Exception
     */
    public static int sendTempMsg(String accessToken,WxTemplateMsg templateMsg ) throws Exception {
        //数据校验
        if (StringUtils.isBlank(accessToken)) {
            throw new ServiceException("WXMSG-001");
        }
        if (StringUtils.isBlank(templateMsg.getTouser())) {
            throw new ServiceException("WXMSG-002");
        }
        if (StringUtils.isBlank(templateMsg.getTemplateId())) {
            throw new ServiceException("WXMSG-003");
        }
        if (null != templateMsg.getMiniprogram()) {
            if (StringUtils.isBlank(templateMsg.getMiniprogram().getAppid())) {
                throw new ServiceException("WXMSG-004");
            }
        }
        if (null == templateMsg.getData()) {
            throw new ServiceException("WXMSG-005");
        }
        String tMsgJson = JsonUtil.toString(templateMsg);
        // 请求路径
        String requestUrl = SEND_TEMPMSG_URL.replace("ACCESS_TOKEN", accessToken);
        // 调用接口创建菜单
        JSONObject jsonObject = WeixinHttpUtil.httpRequest(requestUrl, "POST", tMsgJson);
        WxExceptionUtil.parse(jsonObject.toJSONString());
        int result = 1;
        return result;
    }

    /**
     * 群发消息
     *
     * @author lujiang
     * @date 2019-03-12
     * @param access_token 全局唯一接口调用凭据
     * @param wxMessage 消息对象
     * @return
     * @throws Exception
     */
    public static int sendMsg(String access_token, WxMessage wxMessage) throws Exception {
        if (StringUtils.isBlank(access_token)) {
            throw new Exception("access_token不能为空！");
        }
        Map<String, Object> map = new HashMap<>(16);
        // 发送内容
        String contents = wxMessage.getContents();
        map.put("touser",wxMessage.getOpenIds());
        if (StringUtils.equals(wxMessage.getMsgType(),"text")) {
            // 文本
            Map<String, Object> textMap = new HashMap<>(16);
            textMap.put("content", contents);
            map.put("text", textMap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"image")) {
            // 图片
            Map<String, Object> mediaIdmap = new HashMap<>(16);
            mediaIdmap.put("media_id", contents);
            map.put("image", mediaIdmap);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"mpnews")) {
            // 图文
            Map<String, Object> mpnewsmap = new HashMap<>(16);
            mpnewsmap.put("media_id", contents);
            map.put("mpnews", mpnewsmap);
            map.put("send_ignore_reprint",0);
        } else if (StringUtils.equals(wxMessage.getMsgType(),"wxcard")) {
            // 卡券
            Map<String, Object> wxcardmap = new HashMap<>(16);
            wxcardmap.put("card_id", contents);
            map.put("wxcard", wxcardmap);
        }
        map.put("msgtype", wxMessage.getMsgType());
        // 数据json字符串
        String msgJson = JsonUtil.toString(map);
        // 请求路径
        String requestUrl = SENDALL_URL.replace("ACCESS_TOKEN", access_token);
        // 调用接口创建菜单
        JSONObject jsonObject = WeixinHttpUtil.httpRequest(requestUrl, "POST", msgJson);
        WxExceptionUtil.parse(jsonObject.toJSONString());
        return 1;
    }

    /**
     * 根据标签进行群发
     *
     * @author lujiang
     * @date 2019-05-23
     * @param access_token 全局唯一标识
     * @param jsonString 请求参数字符串
     * @return
     * @throws Exception
     */
    public static int sendAllForTag(String access_token, String jsonString) throws Exception {
        if (StringUtils.isBlank(access_token)) {
            throw new Exception("access_token不能为空！");
        }
        if (StringUtils.isBlank(jsonString)) {
            throw new Exception("请求参数不能为空！");
        }
        // 请求路径
        String requestUrl = SENDALL_TAG_URL.replace("ACCESS_TOKEN", access_token);
        // 调用接口创建菜单
        JSONObject jsonObject = WeixinHttpUtil.httpRequest(requestUrl, "POST", jsonString);
        WxExceptionUtil.parse(jsonObject.toJSONString());
        return 1;
    }

    /**
     * 订阅消息发送
     *
     * @author lujiang
     * @date 2019-11-27
     * @param access_token 全局唯一标识
     * @param sendTempMessage 请求参数
     * @return
     * @throws Exception
     */
    public static int subscribeMessageSend(String access_token, SendTempMessage sendTempMessage) throws Exception {
        if (StringUtils.isBlank(access_token)) {
            throw new Exception("BUS-MPMSG-01");
        }
        if (sendTempMessage == null) {
            throw new Exception("BUS-MPMSG-02");
        }
        if (StringUtils.isBlank(sendTempMessage.getOpenId())) {
            throw new Exception("BUS-MPMSG-03");
        }
        if (StringUtils.isBlank(sendTempMessage.getTemplateId())) {
            throw new Exception("BUS-MPMSG-04");
        }
        if (null == sendTempMessage.getData()) {
            throw new Exception("BUS-MPMSG-05");
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("touser",sendTempMessage.getOpenId());
        map.put("template_id",sendTempMessage.getTemplateId());
        if (StringUtils.isNotBlank(sendTempMessage.getPageUrl())) {
            map.put("page",sendTempMessage.getPageUrl());
        }
        map.put("data",sendTempMessage.getData());
        // 数据json字符串
        String msgJson = JsonUtil.toString(map);
        logger.info("订阅消息内容：" + msgJson + "；openid：" + sendTempMessage.getOpenId());
        // 请求路径
        String requestUrl = SEND_SUB_MSG_URL.replace("ACCESS_TOKEN", access_token);
        // 调用接口创建菜单
        JSONObject jsonObject = WeixinHttpUtil.httpRequest(requestUrl, "POST", msgJson);
        logger.info("请求结果：" + jsonObject);
        WxExceptionUtil.parse(jsonObject.toJSONString());
        return 1;
    }
}
